package com.example.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CASDemo2 {
    public static void main(String[] args) {
        AtomicStampedReference<Integer> reference = new AtomicStampedReference<>(1,1);

        new Thread(()->{
            int stamp = reference.getStamp();
            System.out.println("a1->"+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("a="+reference.compareAndSet(1, 2,
                    stamp, stamp + 1));
            System.out.println("a2->"+reference.getStamp());
            System.out.println("a="+reference.compareAndSet(2, 1,
                    reference.getStamp(), reference.getStamp() + 1));
            System.out.println("a3->"+reference.getStamp());
        },"A").start();

        new Thread(()->{
            int stamp = reference.getStamp();
            System.out.println("b1->"+stamp);
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("b2->"+reference.getStamp());
            System.out.println("b="+reference.compareAndSet(1, 6,
                    stamp, stamp + 1));
            System.out.println("b3->"+reference.getStamp());
        },"B").start();

    }
}
